package cn.itsource.ymjs.service.impl;

import cn.itsource.ymjs.entity.SystemItem;
import cn.itsource.ymjs.query.CourseQuery;
import org.hibernate.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import cn.itsource.ymjs.repository.SystemRepository;
import cn.itsource.ymjs.service.ISystemService;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.List;

/**
 * @author 11695
 */
@Transactional(rollbackFor = Exception.class)
@Service
public class SystemServiceImpl extends BaseServiceImpl<SystemItem, CourseQuery> implements ISystemService {

    @Autowired
    private SystemRepository systemRepository;

    /**======================================================================================
     * 方法描述：查询方法在父类，这个构造自己的查询条件
     ======================================================================================*/
    @Override
    protected Specification createWhereForSelectPage(CourseQuery courseQuery) {
        return new Specification<System>(){
            @Override
            public Predicate toPredicate(Root<System> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
                if(courseQuery.getKeyword() != null){
                    //关键字模糊查询
                    Predicate p1 = criteriaBuilder.like(root.get("name").as(String.class), "%"+courseQuery.getKeyword()+"%");
                    query.where(criteriaBuilder.and(p1));
                }
                return query.getRestriction();
            }
        };
    }

    @Override
    public List<SystemItem> getAllGrades() {

        return systemRepository.findByType(1L);
    }
}
